    //
//  TreeViewController.m
//  MClient
//
//  Created by Wang Fei on 10-7-22.
//  Copyright 2010 __MyCompanyName__. All rights reserved.
//

#import "TreeViewController.h"
#import "MServerDAO.h"
#import "MCFunction.h"

@interface TreeViewController (Private)
- (void)removeChildTreeNodes:(NSString *)positionId;
@end

@implementation TreeViewController

@synthesize treeData;
@synthesize treeNodes;
@synthesize treeNodePosition;

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
	[super viewDidLoad];
	[self leftBarButton:@"返回" withStyle:UIBarButtonItemStylePlain selector:@selector(selectCancelAction:)];
	self.title = [treeData objectForKey:@"lbl"];
	self.treeNodes = [treeData objectForKey:@"ns"];
	
	if (treeNodes == nil) {
		treeNodes = [[NSMutableArray alloc]init];
	}
	for (int i = 0; i < [treeNodes count]; i++) {
		NSMutableDictionary *treeNode = [treeNodes objectAtIndex:i];
		[treeNode setObject:@"0" forKey:@"expanded"];
		[treeNode setObject:[NSNumber numberWithInteger:0] forKey:@"stage"];
		[treeNode setObject:[NSNumber numberWithInteger:i] forKey:@"index"];
		[treeNode setObject:[NSNumber numberWithInteger:i] forKey:@"position"];
	}
	self.addHelpButton = YES;
	self.helpUrl = @"/iphone/help/chapter06.html";
	self.tableview.separatorStyle = UITableViewCellSeparatorStyleNone;
	self.tableview.backgroundColor = [UIColor clearColor];
}

- (void)dealloc {
	[treeData release];
	[treeNodes release];
	[treeNodePosition release];
    [super dealloc];
}


#pragma mark -----绘制UITableView,以及UITableView事件-----
//TableView的行数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
	return [treeNodes count];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
	return 32;
}

//初始化TableVie根据参数和数据绘制每一行以及填充数据
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
	int row = [indexPath row];
	static NSString *menuCellIdentifier = @"TreeViewCellIdentifier";
	UITableViewCell *cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:menuCellIdentifier] autorelease];
	cell.backgroundColor = [UIColor clearColor];
	cell.accessoryType = UITableViewCellAccessoryNone;
	cell.selectionStyle = UITableViewCellSelectionStyleBlue;//选中行的颜色
	
	NSMutableDictionary *treeNode = [self.treeNodes objectAtIndex:row];
	NSMutableDictionary *params = [treeNode objectForKey:@"param"];
	if (params != nil) {
		NSMutableDictionary *url = [params objectForKey:@"link"];
		if (url != nil && ![@"empty_url" isEqualToString:[url objectForKey:@"actionType"]]) {
			cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
		}
	}
	int stage = 0;
	UIButton *button = [[UIButton alloc] init];
	if ([treeNode objectForKey:@"hc"]) {
		bool hasChild = [[treeNode objectForKey:@"hc"]boolValue];
		if (hasChild || [treeNode objectForKey:@"ns"]) {
			if ([[treeNode objectForKey:@"expanded"] isEqualToString:@"0"]) {
				[button setBackgroundImage:[UIImage imageNamed:@"tree_plus.png"] forState:UIControlStateNormal];
			}else {
				[button setBackgroundImage:[UIImage imageNamed:@"tree_minus.png"] forState:UIControlStateNormal];
			}
		}else {
			[button setBackgroundImage:[UIImage imageNamed:@"tree_nochild.png"] forState:UIControlStateNormal];
            
		}
	}
	
	if ([treeNode objectForKey:@"stage"]) {
		stage = [[treeNode objectForKey:@"stage"] intValue];
	}
	button.frame = CGRectMake(6.0f + (stage * 20), 4.0f, 24, 24);
	button.tag = row;
	[button addTarget:self action:@selector(doAction:) forControlEvents:UIControlEventTouchUpInside];
	[cell addSubview:button];
	[button release];
	
	UIButton *folder = [[UIButton alloc] init];
	
	if ([treeNode objectForKey:@"hc"]) {
		bool hasChild = [[treeNode objectForKey:@"hc"]boolValue];
		if (hasChild || [treeNode objectForKey:@"ns"]) {
			if ([[treeNode objectForKey:@"expanded"] isEqualToString:@"0"]) {
				[folder setBackgroundImage:[UIImage imageNamed:@"folder_close.png"] forState:UIControlStateNormal];
			}else {
				[folder setBackgroundImage:[UIImage imageNamed:@"folder_open.png"] forState:UIControlStateNormal];
			}
		}else {
			[folder setBackgroundImage:[UIImage imageNamed:@"tree_nochild.png"] forState:UIControlStateNormal];
		}
	}
	folder.frame = CGRectMake(30.0f + (stage * 20), 1.0f, 30, 30);
	folder.tag = row;
	[folder addTarget:self action:@selector(doAction:) forControlEvents:UIControlEventTouchUpInside];
	[cell addSubview:folder];
	[folder release];
	
	CGRect tRect1 = CGRectMake(65.0f + (stage * 20), 0.0f, 280.0f, 32.0f);
	
	id treeLabel = [[UILabel alloc] initWithFrame:tRect1];
	((UILabel*)treeLabel).backgroundColor = [UIColor clearColor];
	NSString *label = [treeNode objectForKey:@"lbl"];
	[treeLabel setText:label];
	[treeLabel setTextAlignment:UITextAlignmentLeft];
	[treeLabel setFont:[UIFont fontWithName:@"Georgia" size:18.0f]];
	[treeLabel setNumberOfLines:1];
	[cell addSubview:treeLabel];
	[treeLabel release];
	
	return cell;
}

-(void)doAction:(id)inSender {
	@try{
		UIButton *b = (UIButton *)inSender;
		int row = b.tag;
		if (treeNodePosition) {
			[treeNodePosition release];
			treeNodePosition = nil;
		}
		self.treeNodePosition = [self.treeNodes objectAtIndex:row];
		int stage = [[treeNodePosition objectForKey:@"stage"]intValue];
		int position = [[treeNodePosition objectForKey:@"position"]intValue];

		if ([treeNodePosition objectForKey:@"ns"]) {
			if([[treeNodePosition objectForKey:@"expanded"] isEqualToString:@"1"]){
				[self removeChildTreeNodes:[treeNodePosition objectForKey:@"id"]];
				[treeNodePosition setObject:@"0" forKey:@"expanded"];
				for(int i = 0; i< [self.treeNodes count]; i++){
					NSMutableDictionary *tempTreeNode = [self.treeNodes objectAtIndex:i];
					[tempTreeNode setObject:[NSNumber numberWithInteger:i] forKey:@"position"];
				}
				[self.tableview reloadData];
				return;
			}
		}
		if (![treeNodePosition objectForKey:@"ns"]) {
			if([treeNodePosition objectForKey:@"hc"]){
				bool hasChild = [[treeNodePosition objectForKey:@"hc"]boolValue];
				if(hasChild){
					[[MServerDAO sharedInstance] getNodeAsync:[treeNodePosition objectForKey:@"nid"] == nil?@"":[treeNodePosition objectForKey:@"nid"]
													   treeId:[treeNodePosition objectForKey:@"id"] == nil?@"":[treeNodePosition objectForKey:@"id"] 
												  queryFilter:[treeNodePosition objectForKey:@"ft"] == nil?[[NSMutableArray alloc]init]:[treeNodePosition objectForKey:@"ft"]
														param:[treeNodePosition objectForKey:@"param"] == nil?[[NSMutableDictionary alloc]init]:[treeNodePosition objectForKey:@"param"]
													 delegate:self];
					
				}
			
			}
		}else {
			if([[treeNodePosition objectForKey:@"expanded"] isEqualToString:@"0"]){
				NSMutableArray *childTreeNodes = [treeNodePosition objectForKey:@"ns"];
			
				for(int j = 0; j < [childTreeNodes count]; j++ ){
					[[childTreeNodes objectAtIndex:j] setObject:[NSNumber numberWithInteger:stage + 1] forKey:@"stage"];
					[[childTreeNodes objectAtIndex:j] setObject:[treeNodePosition objectForKey:@"index"] forKey:@"index"];
					[[childTreeNodes objectAtIndex:j] setObject:[treeNodePosition objectForKey:@"id"] forKey:@"fatherId"];
					[[childTreeNodes objectAtIndex:j] setObject:@"0" forKey:@"expanded"];
				}
				int currentIndex = position + 1;
				for (int i = 0; i<[childTreeNodes count]; i++) {
					[treeNodes insertObject:[childTreeNodes objectAtIndex:i] atIndex:currentIndex];
					currentIndex++;
				}
				[treeNodePosition setObject:@"1" forKey:@"expanded"];
				for(int i = 0; i< [treeNodes count]; i++){
					NSMutableDictionary *tempTreeNode = [treeNodes objectAtIndex:i];
					[tempTreeNode setObject:[NSNumber numberWithInteger:i] forKey:@"position"];
				}
			
				[self.tableview reloadData];
				return;
			}
		}	
	}@catch (NSException *e) {
		[[MCErrorManagement instance] doError:@"99" 
								returnMessage:[NSString stringWithFormat:@"main: Caught %@: %@", [e name], [e reason]]];
	}	
}

- (void) selectCancelAction: (id) sender {
	[self.navigationController popViewControllerAnimated:YES];
}

#pragma mark -- MCServer2ViewDelegate --

- (void)getDataFromServerSuccess: (NSMutableDictionary *)returnValue {
	
	NSMutableDictionary *treeChildData = [returnValue retain];
	int stage = [[treeNodePosition objectForKey:@"stage"]intValue];
	int position = [[treeNodePosition objectForKey:@"position"]intValue];
	
	NSMutableArray *treeChildNodes = [treeChildData objectForKey:@"ns"];
	if (treeChildNodes) {
		[treeNodePosition setObject:treeChildNodes forKey:@"ns"];
		if([[treeNodePosition objectForKey:@"expanded"] isEqualToString:@"0"]){
			NSMutableArray *childTreeNodes = [treeNodePosition objectForKey:@"ns"]; 
			for(int j = 0; j < [childTreeNodes count]; j++ ){
				[[childTreeNodes objectAtIndex:j] setObject:[NSNumber numberWithInteger:stage + 1] forKey:@"stage"];
				[[childTreeNodes objectAtIndex:j] setObject:[treeNodePosition objectForKey:@"index"] forKey:@"index"];
				[[childTreeNodes objectAtIndex:j] setObject:[treeNodePosition objectForKey:@"id"] forKey:@"fatherId"];
				[[childTreeNodes objectAtIndex:j] setObject:@"0" forKey:@"expanded"];
			}
			int currentIndex = position + 1;
			for (int i = 0; i<[childTreeNodes count]; i++) {
				[treeNodes insertObject:[childTreeNodes objectAtIndex:i] atIndex:currentIndex];
				currentIndex++;
			}
			[treeNodePosition setObject:@"1" forKey:@"expanded"];
			for(int i = 0; i< [treeNodes count]; i++){
				NSMutableDictionary *tempTreeNode = [treeNodes objectAtIndex:i];
				[tempTreeNode setObject:[NSNumber numberWithInteger:i] forKey:@"position"];
			}
			
			[self.tableview reloadData];
			return;
		}
	} else {
		NSMutableDictionary *url = [returnValue objectForKey:@"link"];
		if (url) {
			[MCFunction pushViewByUrl:url parameters:nil confirmMessage:nil naviController:self.navigationController];
		}
	}
}

//每一行选中（点击树）
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
	int row = [indexPath row];
	NSMutableDictionary *treeNode = [treeNodes objectAtIndex:row];
	NSMutableDictionary *params = [treeNode objectForKey:@"param"];
	if (params == nil) {
		UIButton *button = [[UIButton alloc] init];
		button.tag = row;
		[self doAction:button];
		[button release];
		return;
	}
	NSMutableDictionary *url = [params objectForKey:@"link"];
	if (url == nil || [@"empty_url" isEqualToString:[url objectForKey:@"actionType"]]) {
		UIButton *button = [[UIButton alloc] init];
		button.tag = row;
		[self doAction:button];
		[button release];
		return;
	}
	[MCFunction pushViewByUrl:url parameters:nil confirmMessage:nil naviController:self.navigationController];
	[tableView deselectRowAtIndexPath:indexPath animated:YES];
}

- (void)removeChildTreeNodes:(NSString *)positionId {
	for(int i = 0; i < [self.treeNodes count]; i++){
		if(![[treeNodes objectAtIndex:i]objectForKey:@"fatherId"])
			continue;
		if([[[treeNodes objectAtIndex:i]objectForKey:@"fatherId"] isEqualToString:positionId]){
			NSString *fatherId = [[treeNodes objectAtIndex:i]objectForKey:@"id"];
			[treeNodes removeObjectAtIndex:i];		
			i--;
			[self removeChildTreeNodes:fatherId];
		}
	}
}

@end
